package com.yitiao.socket.chatroom.aio;

import com.yitiao.socket.chatroom.CommonConst;
import com.yitiao.socket.chatroom.MyClient;
import lombok.SneakyThrows;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.Future;

public class AioChatClient extends MyClient {
    private AsynchronousSocketChannel clientChannel;

    @SneakyThrows
    private void start() {
        clientChannel = AsynchronousSocketChannel.open();
        Future<Void> connect = clientChannel.connect(new InetSocketAddress(CommonConst.HOST, CommonConst.PORT));
        connect.get();

        new Thread(new AioClientInputHandler(this)).start();

        // 接收消息
        ByteBuffer buffer = ByteBuffer.allocate(CommonConst.BUFFER);
        while (clientChannel.isOpen()){
            Future<Integer> read = clientChannel.read(buffer);
            int result = read.get();
            if(result <= 0){
                //这里是，当我们输入quit时，在服务器端会自动将我们移除
                //所以这里关闭就好了
                clientChannel.close();
            }else {
                buffer.flip();
                String msg = String.valueOf(charset.decode(buffer));
                System.out.println(msg);
                buffer.clear();
            }
        }

    }

    @SneakyThrows
    public void send(String msg){
        if(!msg.isEmpty()){
            ByteBuffer buffer = charset.encode(msg);
            Future<Integer> write = clientChannel.write(buffer);
            write.get();
        }
    }

    public static void main(String[] args) {
        AioChatClient client = new AioChatClient();
        client.start();
    }
}
